<template>
  <div>


    <basic-container>
      <vue-element-loading :active="isActive" spinner="bar-fade-scale" color="#409eff" background-color="rgba(255,255,255,0.2)"/>
      <el-form :inline="true" :model="formReport" >
        <div style="margin-top: 22px">
          <el-form-item>
            <el-select v-model="formReport.gameProjectid" filterable @change="selectProject" clearable placeholder="游戏">
              <el-option
                v-for="item in gamelist"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-date-picker
              v-model="payTime"
              clearable
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="充值开始日期"
              end-placeholder="充值结束日期"
              :default-time="['00:00:00', '23:59:59']"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button icon="el-icon-search" type="primary"  @click="onSubmit">查询</el-button>
            <el-button @click="onRecharge">拨币</el-button>
            <el-button type="primary" plain @click="onLoadBalance">查看余额</el-button>
            <el-button icon="el-icon-download" type="primary" @click="handleExport">导出Excel</el-button>
          </el-form-item>
        </div>
      </el-form>
      <el-row>
        <el-col :span="24">
          <template>
            <el-table
              :data="tableData"
              :summary-method="getSummaries"
              show-summary
              stripe
              style="width: 100%">
              <el-table-column
                prop="depositGrantNo"
                label="流水号">
              </el-table-column>
              <el-table-column
                prop="gameProjectName"
                label="游戏">
              </el-table-column>
              <el-table-column
                prop="balance"
                label="平台币数量">
                <template slot-scope="scope">
                  <span class="skucost-pruice">{{scope.row.balance}}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="memo"
                label="备注">
              </el-table-column>
              <el-table-column
                prop="grantUserAccount"
                label="发放人">
              </el-table-column>
              <el-table-column
                prop="createtime"
                label="发放时间">
              </el-table-column>
            </el-table>
          </template>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.currentPage"
            :page-sizes="[10, 20, 50, 100, 200]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
          </el-pagination>
        </el-col>
      </el-row>


      <el-dialog :title="mode" :visible.sync="dialogBalanceVisible" @close="closeBalanceDialog()" :close-on-click-modal="false" customClass="customWidthCompany">
        <div v-if="dialogBalanceVisible">
          <el-form :inline="true" :model="formBalanceReport" >
            <div>
              <el-form-item label="平台币余额：" prop="surplusBalance">
                <div style="margin-right:30px;text-align: left" v-html="formBalanceReport.balance"></div>
              </el-form-item>

              <el-form-item>
                <el-select v-model="formBalanceReport.gameProjectid" filterable @change="selectBalanceProject" clearable placeholder="游戏">
                  <el-option
                    v-for="item in gamelist"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-search" type="primary"  @click="onLoadBalane">查询</el-button>
              </el-form-item>
            </div>
          </el-form>

          <el-row>
            <el-col :span="24">
              <template>
                <el-table
                  :data="tableBalanceData"
                  stripe
                  style="width: 100%">
                  <el-table-column
                    prop="gameProjectName"
                    label="游戏">
                  </el-table-column>
                  <el-table-column
                    prop="balance"
                    label="平台币余额">
                  </el-table-column>
                </el-table>
              </template>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-pagination
                background
                @size-change="balanceHandleSizeChange"
                @current-change="balanceHandleCurrentChange"
                :current-page="balancePage.currentPage"
                :page-sizes="[10, 20, 50, 100, 200]"
                :page-size="balancePage.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="balancePage.total">
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </el-dialog>


      <el-dialog :title="mode" :visible.sync="dialogFormVisible" @close="closeDialog()" :close-on-click-modal="false" customClass="customWidthCompany">
        <div v-if="dialogFormVisible" style="text-align: center">
          <span style="font-size: 20px;">免责声明：为防止纠纷，请仔细核对游戏信息及发币数量！</span>
          <el-form :inline="true" :model="formGrant" :rules="rules" label-width="150px" class="demo-form-inline" ref="grantForm" style="margin-top: 25px">
            <el-row>
              <el-col>
                <el-form-item  label="游戏：" prop="gameProjectid">
                  <el-select v-model="formGrant.gameProjectid" filterable clearable @change="selectDepositBalance" placeholder="游戏" style="width:350px">
                    <el-option
                      v-for="item in gamelist"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item label="平台币余额：" prop="surplusBalance">
                  <div style="width:350px; text-align: left" v-html="formGrant.surplusBalance"></div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item label="平台币发放数量：" prop="balance" >
                  <el-input  v-model="formGrant.balance" style="width:350px;" onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item prop="memo" label="备注：">
                  <el-input style="width: 350px" type="textarea" :rows="5" clearable v-model="formGrant.memo"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog" style="width: 150px">取 消</el-button>
          <el-button v-loading.fullscreen.lock="fullscreenLoading" type="primary" @click="suer('grantForm')" style="width: 150px">发 放</el-button>
        </div>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>

import {mapGetters} from "vuex";
import axios from "axios";
import VueElementLoading from 'vue-element-loading'
import {cloneObj, parseParam} from "@/util/util";
import {getToken} from "@/util/auth";
import {gameList} from "@/api/game/game";
import {depositGrantList, addDepositGameBalance, selectDepositBalance, depositGrantTotal, depositBalanceTotal, depositBalanceList} from "@/api/game/gameDeposit";
export default {
  name: "headman",

  data() {
    return {
      isActive: false,
      fullscreenLoading: false,
      dialogFormVisible: false,
      dialogBalanceVisible: false,
      formReport: {
        gameProjectid:'',
        startTime:'',
        endTime:''
      },
      page: {
        currentPage: 1,
        pageSize: 20,
        total: '',
      },
      balancePage: {
        currentPage: 1,
        pageSize: 10,
        total: '',
      },
      totalCount:'',
      tableData:[],
      tableBalanceData:[],
      tableTotal:{},
      gamelist:[],
      payTime:[],
      formBalanceReport:{
        gameProjectid:'',
        balance:''
      },
      formGrant: {
        gameProjectid:'',
        surplusBalance:'',
        balance: '',
        memo: ''
      },
      rules: {
        gameProjectid:[
          {required: true, message: '请选择', trigger: 'blur'}
        ],
        balance:[
          {required: true, message: '请输入平台币数量', trigger: 'blur'}
        ]
      }
    };

  },
  components: {
    VueElementLoading
  },
  created() {
    this.nowload()
    this.onSubmit()
  },
  methods: {
    getSummaries() {
      let sums = [];
      sums[0] = '总计(小写)'
      sums[2] = Number(this.totalCount)
      for(let i=0; i<=5; i++) {
        if(sums[i] == undefined) {
          sums[i] = ''
        }
      }
      sums = sums.map(item =>{
        if((typeof item) == "number"){
          return item
        }else{
          return item
        }
      });
      return sums;
    },
    nowload() {
      gameList(this.formInline).then(res => {
        const data = res.data.data;
        this.gamelist = data;
      });
    },
    selectProject(value){
      this.formReport.gameProjectid=value
    },
    selectBalanceProject(value){
      this.formBalanceReport.gameProjectid=value
    },
    selectDepositBalance(value){
      this.formGrant.gameProjectid=value
      if(value != "") {
        selectDepositBalance(Object.assign(this.formGrant)).then(res => {
            var data = res.data;
            if(data.success) {
              this.formGrant.surplusBalance = data.data.balance
            }
          }
        )
      } else {
        this.formGrant.surplusBalance = ""
      }
    },

    onSubmit() {
      this.page.currentPage = 1;
      var startTime = undefined;
      var endTime = undefined;
      this.onLoad(startTime, endTime);
    },
    closeDialog() {
      this.dialogFormVisible = false
      this.formGrant = {
        gameProjectid:'',
          surplusBalance:'',
          balance: '',
          memo: ''
      }
    },
    closeBalanceDialog() {
      this.dialogBalanceVisible = false
      this.formBalanceReport.gameProjectid = ''
    },
    onRecharge(){
      this.dialogFormVisible = true;
      this.mode = '拨币';
    },

    suer(grantForm) {
      this.$refs[grantForm].validate((valid) => {
        if (valid) {
          this.fullscreenLoading=true
          addDepositGameBalance(this.formGrant).then(res => {
            this.loading = false;
            this.fullscreenLoading=false
            this.dialogFormVisible=false
            this.formGrant = {
              gameProjectid:'',
              surplusBalance:'',
              balance: '',
              memo: ''
            }
            if (res.data.success) {
              this.$message({
                type: "success",
                message: res.data.msg
              });
              var startTime = undefined;
              var endTime = undefined;
              this.onLoad(startTime, endTime);
            } else {
              this.$message({
                type: "error",
                message: res.data.msg
              });
            }
          })
        }
      })
    },

    onLoadBalance(){
      this.dialogBalanceVisible = true;
      this.mode = '平台币余额详情';
      this.onLoadBalane();
    },

    handleExport() {
      this.$confirm("是否导出平台币发放数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        var forming={};
        forming = cloneObj(this.formReport)
        if (this.isNotEmpty(this.time)) {
          forming.startTime = this.time[0].getTime()
          forming.endTime = this.time[1].getTime()
        }
        window.location.href = `/api/blade-game/depositmarger/export-depositGrant?blade-auth=${getToken()}&${parseParam(forming)}`;
        this.formReport.startTime =''
        this.formReport.endTime =''
      });
    },
    isNotEmpty(arr) {
      return arr != null && arr.length !== 0
    },
    onLoad(startTime, endTime){
      if (this.isNotEmpty(this.payTime)) {
        startTime = this.payTime[0].getTime()
        endTime = this.payTime[1].getTime()
      }
      this.isActive = true;

      depositGrantList(this.page.currentPage, this.page.pageSize, Object.assign(this.formReport), startTime, endTime).then(res => {
        this.isActive = false;
        const data = res.data.data;
        console.log("res.data.data", res.data.data)
        this.page.total = data.total;
        this.tableData = data.records;
      })
      depositGrantTotal(Object.assign(this.formReport), startTime, endTime).then(res => {
        const data = res.data.data;
        this.totalCount = data.totalCount;
      });
      depositBalanceTotal(Object.assign(this.formBalanceReport)).then(res => {
        const data = res.data.data;
        this.formBalanceReport.balance = data.balance;
      });
    },
    onLoadBalane() {
      depositBalanceList(this.balancePage.currentPage, this.balancePage.pageSize, Object.assign(this.formBalanceReport)).then(res => {
        const data = res.data.data;
        console.log("res.data.data", res.data.data)
        this.balancePage.total = data.total;
        this.tableBalanceData = data.records;
      })
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      var startTime = undefined;
      var endTime = undefined;
      this.onLoad(startTime, endTime);
    },
    handleCurrentChange(val) {

      this.page.currentPage = val;
      var startTime = undefined;
      var endTime = undefined;
      this.onLoad(startTime, endTime);
    },
    balanceHandleSizeChange(val) {
      this.page.pageSize = val;
      this.onLoadBalane();
    },
    balanceHandleCurrentChange(val) {
      this.page.currentPage = val;
      this.onLoadBalane();
    },
  }
};
</script>

<style lang="scss" >

</style>
